package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"strings"

	"gorm.io/gorm"
)

// 获取部门列表
func GetDeptInfoList(info request.QueryDept) (list model.Depts, err error) {
	db := global.GVA_DB.Model(&model.SysDept{})
	var deptList []model.SysDept
	if info.DeptName != "" {
		db = db.Where("dept_name LIKE ?", "%"+strings.TrimSpace(info.DeptName)+"%")
	}
	if info.Status != "" {
		db = db.Where("status = ?", info.Status)
	}

	err = db.Find(&deptList).Error
	return deptList, err
}

// 新增部门
func CreateDept(dept model.SysDept) (err error) {
	if !errors.Is(global.GVA_DB.First(&dept, "dept_name = ?", dept.DeptName).Error, gorm.ErrRecordNotFound) {
		return errors.New("部门名称已存在")
	}

	err = global.GVA_DB.Create(&dept).Error
	return err
}

// 查询部门
func QueryDept(id uint64) (dept model.SysDept, err error) {
	err = global.GVA_DB.First(&dept, id).Error
	return dept, err
}

// 更新部门
func UpdateDept(dept model.SysDept) (err error) {
	db := global.GVA_DB.Model(&model.SysDept{}).Where("dept_id = ?", dept.DeptId)
	if errors.Is(db.Error, gorm.ErrRecordNotFound) {
		return errors.New("找不到对应的部门")
	}

	err = db.Updates(&dept).Error
	return err
}

// 删除部门
func DeleteDept(deptId string) (err error) {
	db := global.GVA_DB
	if !errors.Is(db.First(&model.SysRoleDept{}, "dept_id = ?", deptId).Error, gorm.ErrRecordNotFound) {
		return errors.New("数据使用中无法删除")
	}

	err = db.Where(deptId).Delete(&model.SysDept{}).Error
	return err
}
